<template>
  <div>
    <div class="-mt-46 h-[calc(100vh-15px)] pt-46 flex flex-col">
      <div
        ref="scrollContainer"
        class="scroll-view scroll-view--vertical hide-scrollbar flex-1"
      >
        <div ref="scrollContent" class="scroll-view__content">
          <!-- 加载状态 -->
          <div v-if="isLoading" class="py-20 flex justify-center items-center">
            <van-loading size="24px" vertical>
              <span class="text-13 text-999 mt-10">加载中...</span>
            </van-loading>
          </div>
          <div class="pb-15 px-15">
            <div
              v-for="item in historyData.records"
              :key="item.id"
              class="mb-25 flex flex-col text-white"
            >
              <div class="text-999999 text-12 self-center">
                {{ item.createTime }}
              </div>
              <div
                class="select-text c-animation-opacity ml-50 mt-15 mx-10 px-15 py-10 leading-28 rounded-15 bg-1F1F61 text-14"
              >
                主题描述：{{ item.title }}
              </div>
              <div class="mt-5 text-13 text-999999 text-right">
                {{ item.model }}
              </div>
              <div
                v-if="item.status === AI_COPY_STATUS_ENUM.DONE"
                class="c-animation-opacity mr-50 mt-15 py-10 px-15 rounded-15 bg-2F2F33"
              >
                <div
                  class="pb-10 leading-30 border-solid border-b-1 border-3D3D3D text-14"
                >
                  <svg-icon name="icon-meihua" :size="16" color="#fff" />
                  <span class="ml-10 whitespace-pre-wrap">{{
                    item.content
                  }}</span>
                </div>
                <div class="pt-10 flex items-center justify-between">
                  <div class="text-13 text-999999">
                    {{ item.content.length }}字
                  </div>
                  <div
                    class="flex items-center"
                    @click="copyContent(item.content)"
                  >
                    <svg-icon name="icon-fuzhi1" :size="16" color="#fff" />
                    <div class="ml-6 text-13">复制</div>
                  </div>
                </div>
              </div>
              <div
                v-if="item.status === AI_COPY_STATUS_ENUM.GENERATING"
                class="flex items-center mr-50 mt-15 py-10 px-15 rounded-15 bg-2F2F33"
              >
                <div class="loading-circle w-14 h-14 rounded-[50%]" />
                <div class="ml-10 text-14 leading-30">文案生成中...</div>
              </div>
            </div>
          </div>
          <!-- 暂无数据 -->
          <EmptyState
            v-if="!isLoading && historyData.records.length === 0"
            class="mt-100"
          />
        </div>
      </div>
    </div>
    <!-- 复制成功提示 -->
    <van-toast v-model:show="showCopySuccess" message="复制成功" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, onBeforeUnmount } from "vue";
import type { PageResponse } from "src/types";
import { showToast } from "vant";
import {
  getAiTextList,
  AiTextInfoData,
  getAiText
} from "@/api/AiCopyGenHistory";
import { useClipboard } from "@vueuse/core";
import { AI_COPY_STATUS_ENUM } from "@/constants";

defineOptions({
  name: "AiCopyGenHistory"
});

// 复制相关
const showCopySuccess = ref(false);
const { copy, isSupported } = useClipboard();

// 复制内容
const copyContent = (content: string) => {
  if (content) {
    if (isSupported) {
      copy(content);
      showCopySuccess.value = true;
    } else {
      showToast("您的浏览器不支持复制功能");
    }
  }
};

// 历史记录数据
const historyData = ref<PageResponse<AiTextInfoData>>({
  current: 1,
  pages: 0,
  records: [],
  size: 24,
  total: 0
});

// 加载状态
const isLoading = ref(false);
const isFinished = ref(false);

// 滚动容器引用
const scrollContainer = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null);

// 轮询定时器存储对象
const pollingTimers = ref<Record<string, number>>({});
// 组件卸载标志
let isUnmounted = false;

// 检查并启动状态为2的记录轮询
const checkAndStartPolling = () => {
  historyData.value.records.forEach(record => {
    if (record.status === AI_COPY_STATUS_ENUM.GENERATING) {
      startPolling(record.id);
    }
  });
};

// 启动轮询
const startPolling = (itemId: string) => {
  // 如果已经在轮询，则不再重复启动
  if (pollingTimers.value[itemId]) return;

  const poll = async () => {
    if (isUnmounted) return;

    try {
      const detail = await getAiText(itemId);
      if (isUnmounted) return;

      const recordIndex = historyData.value.records.findIndex(
        r => r.id === itemId
      );
      if (recordIndex !== -1) {
        // 更新记录
        historyData.value.records[recordIndex] = {
          ...historyData.value.records[recordIndex],
          ...detail
        };

        // 如果状态变为完成，清除定时器
        if (detail.status === AI_COPY_STATUS_ENUM.DONE) {
          clearPollingTimer(itemId);
        } else {
          // 继续轮询
          pollingTimers.value[itemId] = window.setTimeout(poll, 1500);
        }
      } else {
        clearPollingTimer(itemId);
      }
    } catch (error) {
      if (isUnmounted) return;
      console.error("轮询出错:", error);
      // 出错后继续轮询
      pollingTimers.value[itemId] = window.setTimeout(poll, 3000);
    }
  };

  // 立即开始轮询
  poll();
};
// 清除单个轮询定时器
const clearPollingTimer = (itemId: string) => {
  if (pollingTimers.value[itemId]) {
    clearTimeout(pollingTimers.value[itemId]);
    delete pollingTimers.value[itemId];
  }
};
// 清除所有轮询定时器
const clearAllPollingTimers = () => {
  Object.keys(pollingTimers.value).forEach(itemId => {
    clearTimeout(pollingTimers.value[itemId]);
  });
  pollingTimers.value = {};
};
// 加载函数
const loadHistoryData = async (loadMore = false) => {
  if (isLoading.value) return;

  try {
    isLoading.value = true;
    const currentData = historyData.value;

    // 计算下一页页码（加载更多时页码+1）
    const nextPage = loadMore ? currentData.current + 1 : 1;
    const params = {
      pageNo: nextPage,
      pageSize: 24
    };

    const res = await getAiTextList(params);
    // 对records进行倒序处理
    const reversedRecords = res.records.reverse();

    historyData.value = loadMore
      ? {
          ...res,
          records: [...reversedRecords, ...currentData.records]
        }
      : {
          ...res,
          records: reversedRecords
        };

    isFinished.value = res.current >= res.pages;

    // 初始加载后滚动到底部
    if (!loadMore) {
      nextTick(() => {
        if (scrollContainer.value && scrollContent.value) {
          scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
        }
      });
    } else if (res.records.length > 0) {
      showToast({
        message: `加载了 ${res.records.length} 条新记录`,
        position: "top"
      });
    }
  } catch (error) {
    console.error("加载失败:", error);
    showToast("加载失败，请稍后再试");
  } finally {
    isLoading.value = false;
    // 检查是否有需要轮询的记录
    nextTick(checkAndStartPolling);
  }
};

// 处理滚动事件 - 修改为上拉顶部加载更多
const handleScroll = () => {
  if (!scrollContainer.value || isLoading.value || isFinished.value) return;

  const scrollTop = scrollContainer.value.scrollTop;

  // 当滚动到顶部时触发加载更多
  if (scrollTop <= 50) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
    loadHistoryData(true);
  }
};

onMounted(() => {
  // 初始加载数据
  loadHistoryData();

  nextTick(() => {
    if (scrollContainer.value) {
      scrollContainer.value.addEventListener("scroll", handleScroll);
    }
  });
});

onBeforeUnmount(() => {
  isUnmounted = true;

  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }

  // 清除所有轮询定时器
  clearAllPollingTimers();
});
</script>

<style scoped lang="less">
.scroll-view__content {
  padding-bottom: 20px;
}
</style>
